layui.use(['form', 'layer', 'table', 'laytpl', 'laydate'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table,
        laydate = layui.laydate;

    //日期
    laydate.render({
        elem: '#startdate'
    });
    laydate.render({
        elem: '#enddate'
    });

    //角色列表
    var tableIns = table.render({
        elem: '#rebateList',
        url: '/RebateRecord/LoadData/',
        parseData: function (res) { //res 即为原始返回的数据

            var totalData = res.totalData
            $("#txtTotalQuantity").html(totalData.TotalQuantity);
            $("#txtTotalRebateMoney").html(totalData.TotalRebateMoney);
            $("#txtTotalRebateRMBMoney").html(totalData.TotalRebateRMBMoney);
           
            return res;
        },
        cellMinWidth: 95,
        page: true,
        height: "h-100",
        limits: [10, 15, 20, 25],
        limit: 10,
        id: "rebateListTable",
        cols: [[
            { type: "checkbox", fixed: "left", width: 50 },
            { field: "Id", title: '编号', width: 80, align: "center"},
            { field: 'ManagerName', title: '直客帐号2', minWidth: 70, align: "center", templet: '<span>{{ d.ManagerName }}({{ d.ManagerRealName }})</span>', totalRowText: "列合计" },
            { field: 'ParentManagerName', title: '上级代理', minWidth: 70, align: "center", templet: '<span>{{ d.ParentManagerName }}({{ d.PManagerRealName }})</span>' },
            { field: 'ServiceChargeMoney', title: '手续费(单边)', minWidth: 40, align: "center", totalRow: true },
            { field: 'TransactionNo', title: '成交编号', width: 70, align: "center" },
            { field: 'TransactionTime', title: '成交时间', width: 180, align: "center" },
            { field: 'Quantity', title: '开平数量', minWidth: 40, align: 'center', totalRow: true },
            { field: 'Currency', title: '货币类型', minWidth: 40, align: 'center' },
            { field: 'ProjectName', title: '产品名称', minWidth: 40, align: 'center', templet: '<span>{{ d.ProjectName }}({{ d.ProjectCode }})</span>' },
            { field: 'RebateMoney', title: '返佣金额', minWidth: 40, align: 'center', totalRow: true },
            { field: 'RebateRMBMoney', title: 'RMB金额', minWidth: 40, align: 'center', totalRow: true },
            { field: 'Remark', title: '备注', align: 'center' },
            { title: '操作', minWidth: 50, templet: '#rebateListBar', fixed: "right", align: "center" }
        ]],
        totalRow: true  //开启合计行
    });

    var userInfo = JSON.parse(window.sessionStorage.getItem('userInfo'));
    if (userInfo) {
        // 只有一二级代理可以注册代理，中级代理只能注册直客
        if (userInfo.roleId == 3 || userInfo.roleId == 4 || userInfo.roleId == 5) {
            $(".code_btn").show();
        } else if (userInfo.roleId == 1 || userInfo.roleId == 2) {
            $(".addManager_btn, .delAll_btn").show();
        }
    }

    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】
    $(".search_btn").on("click", function () {
        //if ($(".searchVal").val() !== '' || $(".startdate").val() !== '' || $(".enddate").val() !== '') {
            table.reload("rebateListTable", {
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    key: $(".searchVal").val(),  //搜索的关键字
                    state: $(".searchState").val(),
                    start: $(".startdate").val(),
                    end: $(".enddate").val(),
                    searchDateType: $("input[name='searchDateType']:checked").val()
                }
            });
        //} else {
        //    layer.msg("请输入搜索的内容");
        //}
    });

    //添加用户
    function addManager(edit) {
        var tit = "添加用户";
        if (edit) {
            tit = "编辑用户";
        }
        var index = layui.layer.open({
            title: tit,
            type: 2,
            anim: 1,
            area: ['500px', '90%'],
            content: "/RebateRecord/AddOrModify/",
            success: function (layero, index) {
                var body = layui.layer.getChildFrame('body', index);
                if (edit) {
                    body.find("#Id").val(edit.Id);
                    body.find(".UserName").val(edit.UserName);
                    body.find(".NickName").val(edit.NickName);
                    body.find(".RoleId").val(edit.RoleId);
                    body.find(".Mobile").val(edit.Mobile);
                    body.find(".Email").val(edit.Email);
                    body.find("input:checkbox[name='IsLock']").prop("checked", edit.IsLock);
                    body.find(".Remark").text(edit.Remark || '');
                    form.render();
                }
            }
        });
    }

    function previewManager(edit) {
        var tit = "查看用户";
        var index = layui.layer.open({
            title: tit,
            type: 2,
            anim: 1,
            area: ['500px', '90%'],
            content: "/RebateRecord/Preview/",
            success: function (layero, index) {
                var body = layui.layer.getChildFrame('body', index);
                if (edit) {
                    body.find("#Id").val(edit.Id);
                    body.find(".UserName").val(edit.UserName);
                    body.find(".NickName").val(edit.NickName);
                    body.find(".RoleId").val(edit.RoleId);
                    body.find(".Mobile").val(edit.Mobile);
                    body.find(".Email").val(edit.Email);
                    body.find(".BankType").val(edit.BankType);
                    body.find(".BankCard").val(edit.BankCard);

                    var html = '';
                    for (var i = 0; i < edit.AuditImages.length; i++) {
                        var source = edit.AuditImages[i];
                        var src = 'http://dns.qsgjlive.com/' + source;
                        html += '<a target="_blank" href="' + src + '"><img src="' + src + '" style="width: 60px; height: 60px;margin: 2px;"></a>';
                    }
                    body.find(".auditImages").html(html);
                    
                    body.find("input:checkbox[name='IsLock']").prop("checked", edit.IsLock);
                    body.find(".Remark").text(edit.Remark || '');
                    form.render();
                }
            }
        });
    }

    
    $(".addManager_btn").click(function () {
        addManager();
    });

    //批量删除
    $(".delAll_btn").click(function () {
        var checkStatus = table.checkStatus('rebateListTable'),
            data = checkStatus.data,
            managerId = [];
        if (data.length > 0) {
            for (var i in data) {
                managerId.push(data[i].Id);
            }
            layer.confirm('确定删除选中的用户？', { icon: 3, title: '提示信息' }, function (index) {
                //获取防伪标记
                del(managerId);
            });
        } else {
            layer.msg("请选择需要删除的用户");
        }
    });

    // 我的二维码
    $(".excel_btn").click(function () {
        exportExcel();
    });

    //列表操作
    table.on('tool(rebateList)', function (obj) {
        var layEvent = obj.event,
            data = obj.data;

        if (layEvent === 'preview') { //编辑
            previewManager(data);
        } else if (layEvent === 'edit') { //编辑
            addManager(data);
        } else if (layEvent === 'del') { //删除
            layer.confirm('确定删除此用户？', { icon: 3, title: '提示信息' }, function (index) {
                del(data.Id);
            });
        } else if (layEvent === 'state') {
            //console.log(data);
            layer.confirm('你确认要审核通过吗？', {
                icon: 3,
                title: '审核提示',
                btn: ['通过', '不通过', '取消'],
                btn3: function (index, layero) {
                    layer.close(index);
                },
                cancel: function (index) {
                    layer.close(index);
                }
            }, function (index) {
                audit(data.Id, 1);
                layer.close(index);
            }, function (index) {
                audit(data.Id, 2);
                layer.close(index);
            });
        }
    });

    form.on('switch(IsLock)', function (data) {
        var tipText = '确定锁定当前用户吗？';
        if (!data.elem.checked) {
            tipText = '确定启用当前用户吗？';
        }
        layer.confirm(tipText, {
            icon: 3,
            title: '系统提示',
            cancel: function (index) {
                data.elem.checked = !data.elem.checked;
                form.render();
                layer.close(index);
            }
        }, function (index) {
            changeLockStatus(data.value, data.elem.checked);
            layer.close(index);
        }, function (index) {
            data.elem.checked = !data.elem.checked;
            form.render();
            layer.close(index);
        });
    });

    function del(managerId) {
        $.ajax({
            type: 'POST',
            url: '/RebateRecord/Delete/',
            data: { managerId: managerId },
            dataType: "json",
            headers: {
                "X-CSRF-TOKEN-yilezhu": $("input[name='AntiforgeryKey_yilezhu']").val()
            },
            success: function (data) {//res为相应体,function为回调函数
                var index = layer.msg(data.ResultMsg, {
                    time: 2000 //20s后自动关闭
                }, function () {
                    tableIns.reload();
                    layer.close(index);
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.alert('操作失败！！！' + XMLHttpRequest.status + "|" + XMLHttpRequest.readyState + "|" + textStatus, { icon: 5 });
            }
        });
    }

    function changeLockStatus(managerId, status) {
        $.ajax({
            type: 'POST',
            url: '/RebateRecord/ChangeLockStatus/',
            data: { Id: managerId, IsLock: status },
            dataType: "json",
            headers: {
                "X-CSRF-TOKEN-yilezhu": $("input[name='AntiforgeryKey_yilezhu']").val()
            },
            success: function (data) {//res为相应体,function为回调函数
                layer.msg(data.ResultMsg);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.alert('操作失败！！！' + XMLHttpRequest.status + "|" + XMLHttpRequest.readyState + "|" + textStatus, { icon: 5 });
            }
        });
    }

    function exportExcel() {
        //$.ajax({
        //    type: 'GET',
        //    url: '/RebateRecord/ExportExcel/',
        //    data: {
        //        key: $(".searchVal").val(),  //搜索的关键字
        //        state: $(".searchState").val(),
        //        start: $(".startdate").val(),
        //        end: $(".enddate").val(),
        //        searchDateType: $("input[name='searchDateType']:checked").val()
        //    },
        //    dataType: "json",
        //    headers: {
        //        "X-CSRF-TOKEN-yilezhu": $("input[name='AntiforgeryKey_yilezhu']").val()
        //    },
        //    success: function (data) {//res为相应体,function为回调函数
        //        console.log('导出成功！');
        //    },
        //    error: function (XMLHttpRequest, textStatus, errorThrown) {
        //        layer.alert('操作失败！！！' + XMLHttpRequest.status + "|" + XMLHttpRequest.readyState + "|" + textStatus, { icon: 5 });
        //    }
        //});
        location.href = '/RebateRecord/ExportExcel?key=' + $(".searchVal").val() + '&state=' + $(".searchState").val() + '&start=' + $(".startdate").val() + '&end=' + $(".enddate").val() + '&searchDateType=' + $("input[name='searchDateType']:checked").val();
    }

});
